package com.zxy.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zxy.constant.MessageConstant;
import com.zxy.constant.RedisConstant;
import com.zxy.entity.PageResult;
import com.zxy.entity.QueryPageBean;
import com.zxy.entity.Result;
import com.zxy.pojo.Setmeal;
import com.zxy.pojo.TravelGroup;
import com.zxy.service.SetmealService;
import com.zxy.service.TravelGroupService;
import com.zxy.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.findPage(queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] travelItemIds) {
        try {
            Result result = setmealService.add(setmeal, travelItemIds);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);

        }
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        try {
            // 1.获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            // 2.生成新的文件名称（防止上传同名文件被覆盖）
            int indexOf = originalFilename.lastIndexOf(".");
            String substring = originalFilename.substring(indexOf);
            String fileName = UUID.randomUUID().toString() + substring;
            // 3.调用工具类，上传图片到七牛云
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);

            //*******************补充代码，解决七牛云上垃圾图片的问题******************************************
            // 将上传图片名称存入Redis，居于Redis的set集合存储
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            //********************************************

            // 4.返回结果
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);

        }


    }


}